<template>
  <div class="scan">
    <u-navbar
      bgColor="transparent"
      :autoBack="true"
      @leftClick="handleLeftClick"
      leftIconColor="#ffffff"
    >
      <view slot="center">
        <text style="color: #fff"> 扫一扫</text>
      </view>
    </u-navbar>
    <!--    <nav-bar bgColor="transparent" :supportWhiteBlack="true"></nav-bar>-->
    <camera
      v-if="isAuthorized"
      mode="scanCode"
      class="camera"
      :style="{
        height: `calc(100vh - ${cusTabBarHeight}px)`,
      }"
      @scancode="handleOnScan"
    ></camera>

    <div v-else class="noAuthorized"></div>

    <block v-if="isAuthorized">
      <div class="text" v-if="!isShow">
        <block v-if="type === PAGE_TYPE.DEFAULT">
          <div>请将码放入框内</div>
          <div v-if="industry < 100">支持核销订单、绑定桌码</div>
          <div v-else>支持核销订单</div>
        </block>
        <block v-if="type === PAGE_TYPE.TABLE_CODE_MANAGEMENT">
          <div>请将桌码放入框内</div>
        </block>
        <block v-if="type === PAGE_TYPE.PUB_USER_WRITE_OFF">
          <div>请将核销码放入框内，即可自动扫描</div>
        </block>
      </div>
      <u-transition :show="isShow" mode="fade-up">
        <div class="form">
          <u--form
            labelPosition="left"
            :model="form"
            ref="form1"
            labelWidth="80"
          >
            <u-form-item label="区域" prop="area">
              <div class="select-box" @click="handleShowAreaSelect">
                {{ areaText }}
                <u-icon name="arrow-down" color="#dadbde" />
              </div>
            </u-form-item>
            <u-form-item label="桌位号" prop="tableCode">
              <div class="select-box" @click="handleShowCodeSelect">
                {{ tableCodeText }}
                <u-icon name="arrow-down" color="#dadbde" v-if="hasTableCode" />
              </div>
            </u-form-item>
            <u-form-item>
              <div class="flexAIC">
                <div style="flex: 1" class="marginRight-20">
                  <u-button
                    type="primary"
                    :plain="true"
                    :hairline="true"
                    @click="isShow = false"
                    text="取消"
                  ></u-button>
                </div>
                <div style="flex: 1">
                  <u-button
                    type="primary"
                    text="确定"
                    @click="handleSubmit"
                  ></u-button>
                </div>
              </div>
            </u-form-item>
          </u--form>
        </div>
      </u-transition>
      <u-picker
        @confirm="handleConfirmRange"
        :show="isShowPicker"
        :columns="columns"
        @close="isShowPicker = false"
        keyName="text"
        @cancel="isShowPicker = false"
      />
    </block>

    <u-popup
      :show="showAuthorized"
      :safeAreaInsetBottom="false"
      mode="center"
      round="24rpx"
    >
      <view class="authorized-container">
        <image :src="icon" class="authorized-icon" />
        <div class="title">温馨提示</div>
        <div class="tips">为了向您提供扫码等服务，请您开启相机权限。</div>
        <div class="btn flexAIC">
          <div class="default-button left" @click="showAuthorized = false">
            取消
          </div>
          <button
            open-type="openSetting"
            class="default-button right"
            @click="handleAuthorized"
          >
            确认
          </button>
        </div>
      </view>
    </u-popup>
    <!--    <cus-tab-bar ref="cusTabBarRef" />-->
  </div>
</template>

<script>
import {
  bindDesk,
  getShopArea,
  getTables,
  getTablesExcludeBind,
} from "@/service/api/sp-product";
import { mapState } from "@dcloudio/vue-cli-plugin-uni/packages/vuex3/dist/vuex.common";
import defaultScanMixin from "@/pages/scan/mixins/defaultScanMixin";
import pubUserWriteOffScanMixin from "@/pages/scan/mixins/pubUserWriteOffScanMixin";
import tableCodeManagementScanMixin from "@/pages/scan/mixins/tableCodeManagementScanMixin";
import { PAGE_TYPE } from "@/pages/scan/const";
import { getUrlQuery } from "@/utils/format";
import { debounce } from "@/utils/use-lazy";

export default {
  mixins: [
    defaultScanMixin,
    pubUserWriteOffScanMixin,
    tableCodeManagementScanMixin,
  ],
  data() {
    return {
      PAGE_TYPE,
      debounce,
      cusTabBarHeight: 0,
      isShow: false,
      isShowPicker: false,
      form: {
        tableCode: 0,
        area: 0,
        qrCode: 0,
      },
      areaRange: [],
      tableCodeRange: [],
      columns: [],
      tempFlag: "area",
      areaText: "",
      tableCodeText: "",
      pageType: "",
      isBind: false,
      hasTableCode: false,
      record: {},
      options: null,
      isNoJumpToPage: false, //是否是从页面跳转的
      isAuthorized: true, //授权的
      showAuthorized: false,
      eventChannelOptions: {},
      icon: "https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/39/20230403/90bd42b7-8299-41ff-a6cf-623e16310367.png",
    };
  },
  computed: {
    type({ options }) {
      return options?.type || PAGE_TYPE.DEFAULT; //看常量文件
    },
    ...mapState("sp-common/auth", ["pubUserInfo"]),
    industry({ pubUserInfo }) {
      return Number(pubUserInfo?.pubDomainShopVo?.industry);
    },
  },
  onLoad(options) {
    this.options = options;
    // this.innitCusTabBarHeight();
    // setTimeout(() => {
    //   this.isShow = true;
    // }, 500);
    if (this.type === PAGE_TYPE.DEFAULT) {
      this.fetTableData();
    }
    this.getEventChannel();
  },
  onShow() {
    this.innitCameraAuthorized();
  },
  methods: {
    innitCameraAuthorized() {
      uni.getSetting({
        success: (res) => {
          if (res.authSetting["scope.camera"]) {
            // 用户已经授权访问摄像头
            this.isAuthorized = true;
            this.showAuthorized = false;
          } else {
            // 用户未授权访问摄像头
            this.isAuthorized = false;
            this.showAuthorized = true;
          }
        },
      });
    },
    handleAuthorized() {},
    getEventChannel() {
      const eventChannel = this.getOpenerEventChannel();
      if (JSON.stringify(eventChannel) !== "{}") {
        eventChannel.on("writeOff", (res) => {
          this.eventChannelOptions = res;
          console.log("页面通信", res);
        });
      }
    },
    innitCusTabBarHeight() {
      this.$refs?.cusTabBarRef?.handleGetCusBarHeight().then((res) => {
        if (!res) {
          return this.innitCusTabBarHeight();
        }
        this.cusTabBarHeight = res;
      });
    },
    fetTableData() {
      //获取桌区域和桌位号
      this.fetTableAreaData();
    },
    async fetTableAreaData() {
      let {
        pubUserInfo: {
          pubDomainShopVo: { id: pubDomainShopId },
        },
      } = this;
      const res = await getShopArea({ pubDomainShopId });
      res.map((table) => {
        table.text = table.name;
        table.value = table.id;
        this.areaRange.push(table);
      });
      console.log("区域数据", this.areaRange);
      this.areaText = this.areaRange[0].text;
      this.form.area = this.areaRange[0].value;
      this.$nextTick(() => {
        //获取桌位号
        this.fetTableCodeData();
      });
    },
    async fetTableCodeData() {
      let {
        pubUserInfo: {
          pubDomainShopVo: { id: pubDomainShopId },
        },
      } = this;
      let queryParams = {
        pubDomainShopId,
        pageNum: 1,
        pageSize: 999,
        areaId: this.form.area,
      };
      const { list } = await getTablesExcludeBind({ ...queryParams });
      if (list.length > 0) {
        this.hasTableCode = true;
        list.map((item) => {
          item.text = "桌号" + item.tableNo;
          item.value = item.id;
          this.tableCodeRange.push(item);
        });
        this.tableCodeText = this.tableCodeRange[0].text || "无桌位";
        this.form.tableCode = this.tableCodeRange[0].value || 0;
      } else {
        this.hasTableCode = false;
        this.tableCodeText = "无桌位数据";
        this.form.tableCode = 0;
      }
      console.log("桌码数据", this.tableCodeRange);
    },
    handleOnScan(record) {
      // uni.$u.debounce(this.handleScanCode(record), 1000);
      debounce(() => {
        this.handleScanCode(record);
      }, 1300)();
    },
    handleScanCode(record) {
      this.record = record;
      //默认情况下
      if (this.type === PAGE_TYPE.DEFAULT) {
        const url = "?" + record?.detail?.result;
        const query = getUrlQuery(url);
        if (query.type) {
          this.isNoJumpToPage = true;
          //假如页面不是路由跳转进来的，是直扫的，运用递归进行重新编译
          this.options = query;
          return this.handleScanCode(record);
        }
        this.handleDefaultScan(record);
      }
      //公域用户小程序核销
      if (this.type === PAGE_TYPE.PUB_USER_WRITE_OFF) {
        this.handlePubUserWriteOff(record);
      }

      //桌码管理扫码
      if (this.type === PAGE_TYPE.TABLE_CODE_MANAGEMENT) {
        this.handleTableCodeManagementScan(record);
      }
    },
    handleLeftClick() {
      let pages = getCurrentPages();
      console.log("handleLeftClick==", pages);
      if (pages.length <= 1) {
        this.$Router.replaceAll({
          name: "home",
        });
      } else {
        this.$Router.back(0);
      }
    },
    async handleSubmit() {
      let {
        pubUserInfo: {
          pubDomainShopVo: { id: pubDomainShopId, storeNo },
          mobilePhone,
        },
        form: { tableCode, area, qrCode },
      } = this;
      console.log("提交，", this.form);
      if (this.type === PAGE_TYPE.DEFAULT) {
        //默认情况下
        let params = {
          pubDomainShopId,
          qrCode: qrCode,
          tableId: tableCode,
          storeNo,
          name: area,
          phone: mobilePhone,
        };
        const res = await bindDesk(params).catch((err) => {
          uni.showToast({
            title: err.msg,
            icon: "none",
          });
        });
        if (res?.code === 0) {
          this.isShow = false;
          uni.showToast({
            title: "绑定成功",
            icon: "success",
          });
          // await this.handleScanCode(this.record);
        }
        console.log("绑定", res, params);
      }
    },
    //初始化区域数据到picker
    handleShowAreaSelect() {
      this.columns = [this.areaRange];
      this.tempFlag = "area";
      this.$nextTick(() => {
        this.isShowPicker = true;
      });
    },
    //初始化桌码数据到picker
    handleShowCodeSelect() {
      if (!this.form.area) {
        uni.showToast({
          title: "请选择区域",
          icon: "none",
        });
        return;
      }
      if (!this.hasTableCode) {
        uni.showToast({
          title: "无桌位数据",
          icon: "none",
        });
        return;
      }
      this.columns = [this.tableCodeRange];
      this.tempFlag = "tableCode";
      this.$nextTick(() => {
        this.isShowPicker = true;
      });
    },
    handleConfirmRange(e) {
      const { value } = e;
      if (this.tempFlag === "area") {
        //区域
        this.areaText = value[0]?.text;
        this.form.area = value[0]?.value;
        this.tableCodeRange = [];
        this.form.tableCode = 0;
        this.tableCodeText = "";
        this.$nextTick(() => {
          //获取桌位号
          this.fetTableCodeData();
        });
      }
      if (this.tempFlag === "tableCode") {
        //桌码
        this.tableCodeText = value[0]?.text;
        this.form.tableCode = value[0]?.value;
      }
      this.$nextTick(() => {
        this.isShowPicker = false;
      });
    },
  },
};
</script>

<style scoped lang="scss">
.camera {
  width: 100%;
}
.text {
  position: absolute;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  color: white;
  text-align: center;
}
.form {
  position: absolute;
  bottom: 0;
  width: calc(100% - 40rpx);
  padding: 20rpx;
  background-color: white;
}
.select-box {
  border: 1rpx solid #dadbde;
  padding: 10rpx 20rpx;
  position: relative;
}
.noAuthorized {
  width: 100vw;
  height: 100vh;
  background-color: #000;
}
.authorized {
  &-container {
    width: calc(600rpx - 78 * 2rpx);
    padding: 40rpx 78rpx;
    text-align: center;
    .title {
      font-size: 32rpx;
      font-family: PingFang SC;
      font-weight: bold;
      color: #131313;
      padding: 35rpx 0;
    }
    .tips {
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #131313;
      line-height: 42rpx;
      opacity: 0.7;
      margin-bottom: 35rpx;
      text-align: left;
    }
    .btn {
      justify-content: space-between;
      .default-button {
        width: 212rpx;
        height: 88rpx;
        line-height: 88rpx;
        border: 1px solid #ffb72f;
        border-radius: 44rpx;
        font-size: 28rpx;
      }
      .left {
        font-family: PingFang SC;
        font-weight: 500;
        color: #ffb72f;
      }
      .right {
        color: white;
        background: #ffb72f;
      }
    }
  }
  &-icon {
    width: 183rpx;
    height: 180rpx;
    margin: 0 auto;
  }
}
</style>
